package com.eascs.deploy.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.deploy.entity.O2oDeployFile;
import com.eascs.deploy.entity.O2oDeployFileLink;
import com.eascs.deploy.service.DeployFileService;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Controller
public class DeployFileController extends BaseMasterViewController{
	
	//systemSettings
	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "systemSettings");
	}
	
	@Autowired
	DeployFileService deployFileService;
	
	
	@RequestMapping(value="/startDeploy")
	public String startDeploy(String bankTypeId, String fileTypeId) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "DataConfiguration");
		List<O2oDeployFileLink> deployFiles = deployFileService.deployFile(bankTypeId, fileTypeId);
		List<O2oDeployFile> findAllFiles = deployFileService.findAllFiles();
		
		ViewContext.put("findAllFiles", findAllFiles);
			
		ViewContext.put("deployFiles", deployFiles);
		
		if (bankTypeId != null && fileTypeId != null) {
			return "deploy/ajaxDeployFile";
		}
		return "deploy/deployFile";
	}
	
	@RequestMapping(value="/saveDeploy")
	public String saveDeploy(String files) {
		String[] splits = files.split("/");
		String[] tops = splits[0].split(";");
		String bankTypeId = deployFileService.findId(tops[0]);
		String formTypeId = deployFileService.findId(tops[1]);
		deployFileService.deleteFile(bankTypeId, formTypeId);		
		
		if (splits.length > 1 ) {
			String[] forms = splits[1].split(";");
			for(int i = 0; i < forms.length; i++) {
				O2oDeployFileLink deployFile = new O2oDeployFileLink();
				deployFile.setFiledId(forms[i].split(",")[0]);
				deployFile.setFieldRequired(Integer.parseInt(forms[i].split(",")[1]));
				deployFile.setFieldMin(Integer.parseInt(forms[i].split(",")[2]));
				deployFile.setFiledMax(Integer.parseInt(forms[i].split(",")[3]));
				deployFile.setBankTypeId(bankTypeId);
				deployFile.setFormTypeId(formTypeId);
				deployFile.setCreate_time(new Date());
				User user = UserHolder.getUser();
				deployFile.setCreator(user.getAccount());
				deployFileService.insertFile(deployFile);
				
			}
		}
		
		return "deploy/ajaxDeployFile";
	}

}
